package io.github.codelifeleno.jdbrelease.execute;

import io.github.codelifeleno.jdbrelease.config.DBConfig;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * 数据库操作对象，用于确认数据库是否存在本工具专用的对象
 */
public class DataBaseService {

    private static final Logger log = LoggerFactory.getLogger(DataBaseService.class);
    private final DataSource datasource;
    private DBConfig dbConfig;
    private final QueryRunner queryRunner;


    /**
     * 通过 其他包含管理数据库连接工程使用
     *
     * @param datasource
     */
    public DataBaseService(DataSource datasource) {
        this.datasource = datasource;
        queryRunner = new QueryRunner(datasource);
    }

    /**
     * 通过 api 或者 cli 调用时使用的api
     *
     * @param dbConfig 数据库配置
     */
    public DataBaseService(DBConfig dbConfig) {
        this.dbConfig = dbConfig;
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(dbConfig.getDriver());
        ds.setUrl(dbConfig.getUrl());
        ds.setUsername(dbConfig.getUsername());
        ds.setPassword(dbConfig.getPassword());
        datasource = ds;
        queryRunner = new QueryRunner(ds);
    }

    public boolean execute(String sql) {
        try {
            log.info("Executing SQL: {}", sql);
            int execute = queryRunner.execute(sql);
            log.info("Executed SQL Update: {}", execute);
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
            return false;
        }
        return true;
    }


    public DataSource getDatasource() {
        return datasource;
    }

    public DBConfig getDbConfig() {
        return dbConfig;
    }

    public QueryRunner getQueryRunner() {
        return queryRunner;
    }
}
